package com.wellview.template.modle;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.wellview.template.App;
import com.wellview.template.BaseActivity;
import com.wellview.template.Constant;
import com.wellview.template.R;
import com.wellview.template.bean.UpdateBean;
import com.wellview.template.logger.Logger;
import com.wellview.template.presenter.BaseProvider;
import com.wellview.template.presenter.JSProvider;
import com.wellview.template.presenter.ProviderFactory;
import com.wellview.template.share.ResourcesManager;
import com.wellview.template.utils.FileUtil;
import com.wellview.template.utils.PatternUtils;
import com.wellview.template.utils.ToastUtils;
import com.wellview.template.utils.Utils;
import com.wellview.template.utils.XulUtils;
import com.wellview.template.view.ChooseActivity;
import com.wellview.template.view.CustomScanActivity;
import com.wellview.template.view.LoginActivity;
import com.wellview.template.view.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import okhttp3.Call;


/**
 * Created by Administrator on 2017/8/30 0030.
 */

public class JSBehavior extends BaseBehavior {

    private static String TAG = "JSBehavior";
    private Context context;
    private String functionName;

    private static final String ACTION_LOGOUT = "logout";
    private static final String ACTION_BACK_HOME = "gohome";
    private static final String ACTION_GO_BACK = "goback";
    private static final String ACTION_CALL_PHONE = "tel:";
    private static final String ACTION_OPEN_QR = "openQR";
    private static final String ACTION_MEDIAORDER = "MediaOrder";
    private static final String ACTION_GOODSORDER = "GoodsOrder";
    private static final String ACTION_WECHAT_MEDIA = "&scopes=snsapi_userinfo";
    private static final String ACTION_SEND_LOGIN_STATUS = "sendloginstatus";
    private static final String ACTION_LOAD = "app.moka.cn";
    public static final String ACTION_CHECKUPDATE = "check_update";

    public static final String ACTION_SHARE = "action_share";
    public static final String ACTION_THIRD_PLATFORM_LOGIN = "action_third_login";


    private static final int MSG_SHARE_CANCEL = 2;
    private static final int MSG_SHARE_ERROR = 3;
    private static final int MSG_SHARE_COMPLETE = 4;


    private JSProvider provider;


    public JSBehavior() {
        super(JSProvider.class);
        EventBus.getDefault().register(this);
    }

    public JSBehavior(Context context, String functionName) {
        super(JSProvider.class);
        EventBus.getDefault().register(this);
        this.context = context;
        this.functionName = functionName;
        provider = (JSProvider) ProviderFactory.create(JSProvider.class);
    }

    public JSBehavior(Context context) {
        super(JSProvider.class);
        EventBus.getDefault().register(this);
        this.context = context;
        provider = (JSProvider) ProviderFactory.create(JSProvider.class, this);
    }


    public void handleFunction(String functionName) {
        Logger.i(TAG, "handleFunction functionName is >> " + functionName);
        String function = makeFunction(functionName);
        switch (function) {
            case ACTION_LOGOUT:
                doLogout();
                break;
            case ACTION_BACK_HOME:
                doBackHome();
                break;
            case ACTION_GOODSORDER:
//                doGoodsOrder(functionName);
                break;
            case ACTION_MEDIAORDER:
                doMediaOrder(functionName);
                break;
            case ACTION_OPEN_QR:
                doOpenQR();
                break;
            case ACTION_SEND_LOGIN_STATUS:

                break;
            case ACTION_CALL_PHONE:
                doCallPhone(functionName);
                break;
            case ACTION_GO_BACK:
                doGoback(functionName);
                break;
            case ACTION_CHECKUPDATE:
                doUpdate();
                break;
            case ACTION_SHARE:
                doShare();
            case ACTION_THIRD_PLATFORM_LOGIN:
                doThirdLogin();
                break;
            default:
                break;
        }
    }

    private void doThirdLogin() {

    }

    private void doShare() {
        final cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        final ResourcesManager manager = ResourcesManager.getInstace(context);
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                Logger.i(TAG,"abc "+platform.getName());

                String customText = manager.getText();
                if (TextUtils.isEmpty(customText) ) {
                    customText = context.getString(R.string.share_content);
                }
                if("SinaWeibo".equals(platform.getName())){
                    shareParams.setTitleUrl(manager.getUrl());
                    shareParams.setText(customText);
                    shareParams.setImageUrl(manager.getImageUrl());
//                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                }
                if ("Wechat".equals(platform.getName())) {
                    shareParams.setTitle(customText);
                    shareParams.setUrl(manager.getUrl());
                    shareParams.setText(customText);
                    /*Bitmap imageData = BitmapFactory.decodeResource(getResources(), R.drawable.ssdk_logo);
                    shareParams.setImageData(imageData);*/
                    shareParams.setImageUrl(manager.getImageUrl());
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);

                }
                if ("WechatMoments".equals(platform.getName())) {
                    shareParams.setTitle(customText);
                    shareParams.setUrl(manager.getUrl());
                    shareParams.setText(customText);
                    shareParams.setImageUrl(manager.getImageUrl());
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                }
                if ("QQ".equals(platform.getName())) {
                    Logger.i(TAG,"QQ "+manager.getImageUrl());
                    shareParams.setTitle(customText);
                    shareParams.setTitleUrl(manager.getUrl());
                    shareParams.setText(customText);
                    shareParams.setImageUrl(manager.getImageUrl());
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                }
            }
        });
        oks.setCallback(callback);
        oks.show(context);
    }

    final PlatformActionListener callback = new PlatformActionListener() {
        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            String msg = ResourcesManager.actionToString(i);
            String text = platform.getName() + " completed at " + msg;
            ToastUtils.showToast(context, "分享成功");
            JSONObject sharedJson = getSharedJson(platform.getName(),msg,text,MSG_SHARE_COMPLETE);
            sendToJsWithParamWithFunction(sharedJson.toString(),Constant.JS_FUNCTION_SHARE);
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            String msg = ResourcesManager.actionToString(i);
            String text = platform.getName() + "caught error at " + msg;
            ToastUtils.showToast(context, "分享失败");
            JSONObject sharedJson = getSharedJson(platform.getName(), msg,text,MSG_SHARE_ERROR);
            sendToJsWithParamWithFunction(sharedJson.toString(),Constant.JS_FUNCTION_SHARE);
        }

        @Override
        public void onCancel(Platform platform, int i) {
            String msg = ResourcesManager.actionToString(i);
            String text = platform.getName() + " canceled at " + msg;
            ToastUtils.showToast(context, "分享取消");
            JSONObject sharedJson = getSharedJson(platform.getName(), msg,text,MSG_SHARE_CANCEL);
            sendToJsWithParamWithFunction(sharedJson.toString(),Constant.JS_FUNCTION_SHARE);
        }
    };

    private JSONObject getSharedJson(String name, String msg, String text, int state) {
        JSONObject object = new JSONObject();
        try {
            object.put(msg,msg);
            object.put(text,text);
            object.put("platform",""+name);
            object.put("share_state",""+state);
            object.put("id",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getSharedID()));
            object.put("imageUrl",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getImageUrl()));
            object.put("imagePath",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getImagePath()));
            object.put("filePath",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getFilePath()));
            object.put("title",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getTitle()));
            object.put("url",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getUrl()));
            object.put("titleUrl",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getTitleUrl()));
            object.put("message",""+Uri.encode(ResourcesManager.getInstace(App.getInstance()).getText()));
        }catch (Exception e){
            Logger.i(TAG,"getSharedJson Exception : " + e.getMessage());
        }
        return object;
    }

    /**
     * 升级
     */
    private void doUpdate() {
        if (true) {
            return;
        }
        provider.checkUpdate(new BaseProvider.ResultListener<UpdateBean>() {
            @Override
            public void inProgress(float progress, long total, int id) {

            }

            @Override
            public void onResponse(final UpdateBean bean, int id) {
                if (bean == null) {// error occur
                    Logger.e(TAG, "doUpdate onError occur");
                    return;
                }
                String appVersion = bean.getAppVersion();
                String serverVersionInt = appVersion.replaceAll("[^0-9]*", "");
                PackageInfo packageInfo = Utils.getPackageInfo(App.getInstance());
                String curAppVersion = packageInfo.versionName;
                String curAppVersionInt = curAppVersion.replaceAll("[^0-9]*", "");
                if (XulUtils.tryParseInt(serverVersionInt) <= XulUtils.tryParseInt(curAppVersionInt)) {
                    Logger.i(TAG, "no need to update ...");
                    return;
                }
                Logger.i(TAG, "show update dialog");
                final Dialog dialog = new Dialog(getActivity(), R.style.CustomProgressDialog);
                dialog.setContentView(R.layout.dialog_update);
                dialog.show();
                dialog.setCancelable(false);
                TextView tvVersion = (TextView) dialog.findViewById(R.id.new_version);
                tvVersion.setText("v" + appVersion);
                final ProgressBar pbDownLoad = (ProgressBar) dialog.findViewById(R.id.pb_progress);
                pbDownLoad.setMax(100);
                Button btnCancel = (Button) dialog.findViewById(R.id.btn_cancel);
                final Button btnUpdate = (Button) dialog.findViewById(R.id.btn_update);
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FileUtil.cancelCall(1);
                        dialog.dismiss();
                    }
                });
                btnUpdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        btnUpdate.setEnabled(false);
                        FileUtil.downLoadFile(getActivity().getApplicationContext(), bean.apkFileLocation, "tmp.apk", new FileUtil.DownLoadCallBack() {
                            @Override
                            public void downLoadError(Exception e) {
                                Logger.i(TAG, "升级错误");
                                getActivity().getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        btnUpdate.setEnabled(true);
                                    }
                                });
                            }

                            @Override
                            public void downLoadSuccess(String fileLocation) {
                                Logger.i(TAG, "downLoadSuccess: " + fileLocation);
                                FileUtil.updateApk(context, new File(fileLocation));
                                dialog.dismiss();
                                getActivity().getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        btnUpdate.setEnabled(true);
                                    }
                                });
                            }

                            @Override
                            public void downLoadProgress(final int percent) {
                                Logger.i(TAG, "downLoadProgress: " + percent);
                                getActivity().getHandler().post(new Runnable() {
                                    @Override
                                    public void run() {
                                        pbDownLoad.setProgress(percent);
                                    }
                                });

                            }
                        }, 1);
                    }
                });


            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Logger.e(TAG, "doUpdate onError ");
            }
        });
    }

    public void doUpLoadFile(String extra, String[] filePath) {
        if (TextUtils.isEmpty(extra) || filePath == null || filePath.length == 0) {
            Logger.i(TAG, "doUpLoadFile no file ");
            return;
        }
        Clause clause = new Clause();
        HashMap<String, File> fileMap = new HashMap<>();
        for (String fp : filePath) {
            if (TextUtils.isEmpty(fp)) {
                continue;
            }
            File file = FileUtil.getFileByUri(getActivity(), Uri.parse(fp));
            Logger.i(TAG, "file len is: upload " + file.length());
            String[] split = fp.split("/");
            String name = split[split.length - 1];
            fileMap.put(name, file);
            try {
//                clause.addClause("userAvatar",FileUtil.encodeBase64File(file.getAbsolutePath()));
                clause.files(fileMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        clause.method(Clause.Method.PULL)
                .addCondition(Clause.CONTAINS_FILE, "true")
                .files(fileMap);
//        clause.method(Clause.Method.PULL);
        String url = "";//UploadSubscriberAvatar
//        extra = "{\"url\":\"http://192.168.2.120:8020/Api/Subscriber/UploadSubscriberAvatar\n\n\",\"loginMask\":\"abcdefg\",\"subid\":\"44\"}";
        if (!TextUtils.isEmpty(extra)) {
            try {
                JSONObject jsonObject = new JSONObject(extra);
                url = jsonObject.optString("url");
                Iterator<String> keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String next = keys.next();
                    if ("url".equals(next)) {
                        continue;
                    }
                    String value = jsonObject.optString(next);
                    clause.addClause(next, value);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        if (TextUtils.isEmpty(url)) {
            Logger.e(TAG, "no url");
            return;
        }
        getProvider().setUrl(url)
                .addClause(clause)
                .execute(new BaseProvider.ResultListener<String>() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.i(TAG, "URL_UPLOAD_AVATAR onError >> " + e.getMessage());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Logger.i(TAG, "URL_UPLOAD_AVATAR  onResponse >> " + response);
//                        sendToJsWithParam(response);
                        sendToJsWithParamWithFunction(response,Constant.JS_FUNCTION_UPLOAD_AVATAR);
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        Logger.i(TAG, "URL_UPLOAD_AVATAR  inProgress >> " + progress+"total"+total);
                        ((MainActivity) getActivity()).showGenralProgress((int) ( progress*100),100);
                    }
                });
    }

//    public void sendToJsWithParam(String param) {
//        Logger.i(TAG, "sendToJsWithParam is " + param);
//        WebView webContent = ((MainActivity) getActivity()).getWebContent();
//        if (Build.VERSION.SDK_INT < 18) {
//            webContent.loadUrl("javascript:onAvatarUploadResult(" + param + ")");
//        } else {
//            webContent.evaluateJavascript("javascript:onAvatarUploadResult(" + param + ")", new ValueCallback<String>() {
//                @Override
//                public void onReceiveValue(String value) {
//                    //此处为 js 返回的结果
//                    Logger.i(TAG, "onAvatarUploadResult : value" + value);
//                }
//            });
//        }
//    }

    public void sendToJsWithParamWithFunction(String param,String JSFunction) {
        Logger.i(TAG, "sendToJsWithParamWithFunction is " + param);
        WebView webContent = ((MainActivity) getActivity()).getWebContent();
        if (Build.VERSION.SDK_INT < 18) {
            webContent.loadUrl("javascript:"+JSFunction+"(" + param + ")");
        } else {
            webContent.evaluateJavascript("javascript:"+JSFunction+"(" + param + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                    Logger.i(TAG, "onAvatarUploadResult : value" + value);
                }
            });
        }
    }

    private void doGoback(String functionName) {
        MainActivity activity = (MainActivity) getActivity();
        WebView content = activity.getWebContent();
        Logger.i(TAG, "web content can go back ? " + content.canGoBack());
        if (content.canGoBack()) {
            content.goBack();
        }
    }

    private void doCallPhone(String functionName) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(functionName));
        getActivity().startActivity(intent);
    }

    private void doMediaOrder(String functionName) {
        String[] split = functionName.split("-");
        if (split == null && split.length <= 0) {
            Logger.i(TAG, "doGoodsOrder error");
            return;
        }
        Logger.i(TAG, "split.length()" + split.length);
        if (split.length < 4) {
            Logger.i(TAG, "doGoodsOrder length error");
            return;
        }
        String orderType = split[0];
        String orderNo = split[1];
        String content = split[2];
        String amount = split[3];
//        OurPrepareBean ourPrepareBean = new OurPrepareBean(orderType, orderNo, content, amount);
        HashMap<String, String> pMap = new HashMap<>();
        pMap.put("modSubject", orderType);
        pMap.put("modAmount", amount);
        pMap.put("modOutTradeNO", orderNo);
        Intent intent = new Intent(getActivity(), ChooseActivity.class);
        intent.putExtra("data", pMap);
        getActivity()
                .startActivityForResult(intent
                        , Constant.MESSAGE_REQUEST_METHOD);
    }

    private void handleScanFunction(String scanResult) {
        Logger.i(TAG, "handleScanFunction scanResult is >> " + scanResult);
        String function = makeFunction(scanResult);
        switch (function) {
            case ACTION_MEDIAORDER:
                doMediaOrderScan(scanResult);
                break;
            case ACTION_WECHAT_MEDIA:
                doWechatMediaOrder(scanResult);
                break;
            case ACTION_LOAD:
                doLoadUrl(scanResult);
                break;
            default:
//                doLoadUrl(scanResult);
                break;
        }
    }

    private void doLoadUrl(String scanResultUrl) {
        ((MainActivity) getActivity()).getWebContent().loadUrl(scanResultUrl);
    }

    private void doMediaOrderScan(String scanResult) {
        if (TextUtils.isEmpty(scanResult)) {
            return;
        }
        String[] split = scanResult.split(":");
        if (split.length < 2) {
            return;
        }
        String orderNo = split[1];
//        final String webUrl = Constant.MEDIA_HOST + Constant.MEDIA_ORDER + "=" + orderNo + "&orgin=1";
//        String webUrl = Constant.MEDIA_SCAN.replace("xxx",orderNo);
//        Logger.i(TAG, "webUrl is >> " + webUrl);
//        ((MainActivity)getActivity()).getWebContent().loadUrl(webUrl);
    }

    private void doWechatMediaOrder(String scanResult) {
        if (TextUtils.isEmpty(scanResult)) {
            return;
        }
        Logger.i(TAG, "scanResult " + scanResult);
        String order = PatternUtils.getValueByName(scanResult, "order");
        Logger.i(TAG, "order is >> " + order);
//        String webUrl = Constant.MEDIA_HOST + Constant.MEDIA_ORDER + "=" + order + "&orgin=1";
//        String webUrl = Constant.MEDIA_SCAN.replace("xxx",orderNo);
//        Logger.i(TAG, "webUrl is >> " + webUrl);
//        ((MainActivity)getActivity()).getWebContent().loadUrl(webUrl);
    }

    private void doOpenQR() {
        IntentIntegrator intentIntegrator = new IntentIntegrator(getActivity());
        intentIntegrator
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
                .setPrompt("将二维码/条码放入框内，即可自动扫描")//写那句提示的话
                .setOrientationLocked(false)//扫描方向固定
                .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
                .initiateScan(); // 初始化扫描

    }

    private void doBackHome() {
        Logger.i(TAG, "doBackHome clearHistory and reload host");
//        webView.clearHistory();
//        CookieSyncManager.createInstance(context);  //Create a singleton CookieSyncManager within a context
//        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
//        cookieManager.removeAllCookie();// Removes all cookies.
//        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
//        webView.clearCache(true);
        MainActivity main = (MainActivity) getActivity();
        WebView webContent = main.getWebContent();
        String originalUrl = webContent.getOriginalUrl();
        webContent.clearHistory();
        webContent.loadUrl(main.getCurHomeAddress());

    }

//    private void doGoodsOrder(String functionName) {
//        String[] split = functionName.split("-");
//        if (split == null && split.length <= 0) {
//            Logger.i(TAG,"doGoodsOrder error");
//            return;
//        }
//        Logger.i(TAG,"split.length()"+split.length);
//        if (split.length < 4) {
//            Logger.i(TAG, "doGoodsOrder length error");
//            return;
//        }
//        String orderType = split[0];
//        String orderNo = split[1];
//        String curOrderNo = split[2];
//        String curOrderOrgion = split[3];
//        final PrepareBean prepareBean = new PrepareBean(orderType, orderNo, curOrderNo, curOrderOrgion);
//        prepareBean.setPayTyp(PrepareBean.PAYTYPE_SHOP);
//        HashMap<String, String> pMap = new HashMap<>();
//        pMap.put("way","app");
//        pMap.put("orderid",orderNo);
//        provider.url(Constant.ORDER_PREPARE)
//                .addParam(pMap)
//                .pull(new BaseProvider.DataCallBack() {
//                    @Override
//                    public void onSuccess(Call call, Response response) {
//                        int code = response.code();
//                        if (code == 200) {
//                            try {
//                                String resp = new String(response.body().bytes());
//                                Logger.i(TAG, "resp is >>  " + resp);
//                                JSONObject orderObject = new JSONObject(resp);
//                                handleOrderResult(orderObject, prepareBean);
//                            } catch (Exception e) {
//                                getActivity().getHandler().post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
//                                    }
//                                });
//                                Logger.i(TAG, "该商品暂时不能支付");
//                                e.printStackTrace();
//                            }
//                        } else {
//                            Logger.i(TAG, "该商品暂时不能支付+接口状态码错误");
//                            getActivity().getHandler().post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
//                                }
//                            });
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call call, Exception e) {
//                        Logger.i(TAG, "onFailure e is >>" + e.getMessage());
//                        getActivity().getHandler().post(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                    }
//                });
//    }


    private String makeFunction(String functionName) {
        if (functionName.startsWith(ACTION_LOGOUT)) {
            return ACTION_LOGOUT;
        }
        if (functionName.startsWith(ACTION_SEND_LOGIN_STATUS)) {
            return ACTION_SEND_LOGIN_STATUS;
        }
        if (functionName.startsWith(ACTION_GOODSORDER)) {
            return ACTION_GOODSORDER;
        }
        if (functionName.startsWith(ACTION_BACK_HOME)) {
            return ACTION_BACK_HOME;
        }
        if (functionName.startsWith(ACTION_OPEN_QR)) {
            return ACTION_OPEN_QR;
        }
        if (functionName.startsWith(ACTION_MEDIAORDER)) {
            return ACTION_MEDIAORDER;
        }

        if (functionName.contains(ACTION_LOAD)) {
            return ACTION_LOAD;
        }
        if (functionName.contains(ACTION_CALL_PHONE)) {
            return ACTION_CALL_PHONE;
        }
        if (functionName.endsWith(ACTION_WECHAT_MEDIA)) {
            return ACTION_WECHAT_MEDIA;
        }
        if (functionName.endsWith(ACTION_GO_BACK)) {
            return ACTION_GO_BACK;
        }
        if (functionName.startsWith(ACTION_CHECKUPDATE)) {
            return ACTION_CHECKUPDATE;
        }
        if (functionName.startsWith(ACTION_SHARE)) {
            return ACTION_SHARE;
        }
        return "";
    }

    private void doLogout() {
        Logger.i(TAG, "doLogout >> ");
        if (context instanceof BaseActivity) {
            ((BaseActivity) context).removeLoginMessage();
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            ((BaseActivity) context).finish();
        }
    }


//    private void handleOrderResult(JSONObject orderObject, final PrepareBean prepareBean){
//        String errCode = orderObject.optString("errCode", "");
//        boolean status = orderObject.optBoolean("status", false);
//        String message = orderObject.optString("message", "");
//        JSONObject dataObj = orderObject.optJSONObject("data");
//        if (dataObj == null) {
//            Logger.i(TAG, "order result error no order info >> ");
//            return;
//        }
//        String channel = dataObj.optString("channel");
//        String result = dataObj.optString("result");
//        Logger.i(TAG, "channel is >>" + channel);
//        Logger.i(TAG, "result is >>" + result);
//        if ("wechat".equals(channel)) {
//            try {
//                JSONObject jsonObject = new JSONObject(result);
//                String appid = jsonObject.optString("appid");
//                String partnerid = jsonObject.optString("partnerid");
//                String prepayid = jsonObject.optString("prepayid");
//                String packageStr = jsonObject.optString("package");
//                String noncestr = jsonObject.optString("noncestr");
//                String timestamp = jsonObject.optString("timestamp");
//                String sign = jsonObject.optString("sign");
//                final WechatBean wechatBean = new WechatBean(appid, partnerid, prepayid, packageStr, noncestr, timestamp, sign);
//                getActivity().getHandler().post(new Runnable() {
//                    @Override
//                    public void run() {
//                        PayUtils.getInstance().WechatPay(getActivity(), wechatBean, prepareBean);
//                    }
//                });
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
//        if ("alipay".equals(channel)) {
////            PayUtils.getInstance().Alipay(result, getActivity(),prepareBean);
//        }
//    }


    private BaseActivity getActivity() {
        return (BaseActivity) context;
    }

    public static final int success = 0x2F + 1;
    public static final int failed = 0x2F + 2;
    public static final int cancel = 0x2F + 3;
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void EventBusMessageComein(Object msg) {
//        EventCenter eventCenter = (EventCenter) msg;
//        int resultCode = eventCenter.getResultCode();
//        Logger.i(TAG, ">> msg come in>>" + msg.toString() + "result code is" + resultCode);
//        if (Constant.MESSAGE_PAY_REUSLT == resultCode) {//alipay
//            Logger.i(TAG, ">> msg come in>>" + msg.toString());
//            AlipayResult alipayResult = (AlipayResult) eventCenter.getMsg();
//            PrepareBean prepareBean = alipayResult.getPrepareBean();
//            PayResult result = alipayResult.getResult();
//            int state ;
//            String resultStatus = result.getResultStatus();
//            if ("6001".equals(resultStatus)) {
//                state = cancel;
//            } else if ("9000".equals(resultStatus)) {
//                state = success;
//            } else {
//                state = failed;
//            }
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_SHOP) {
//                handlePayResult(prepareBean, "alipay");
//            }
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_MEDIA) {
//                handleMediaPayResult("alipay", state, prepareBean);
//            }
//        }
//        if (Constant.MESSAGE_PAY_FAILED == resultCode || //wechat pay
//                Constant.MESSAGE_PAY_CANCEL == resultCode) {
//            Logger.i(TAG, ">> msg come in >> MESSAGE_PAY_FAILED or failed " + resultCode);
//            WechatResult wechatResult = (WechatResult) eventCenter.getMsg();
//            PrepareBean prepareBean = wechatResult.getPrepareBean();
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_SHOP) {
//                handlePayResult(prepareBean, "wechat");
//            }
//            int state = 0;
//            if (Constant.MESSAGE_PAY_FAILED == resultCode) {
//                state = failed;
//            } else if (Constant.MESSAGE_PAY_CANCEL == resultCode) {
//                state = cancel;
//            }
//            Logger.i(TAG, "prepareBean.getPayTyp()" + prepareBean.getPayTyp());
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_MEDIA) {
//                handleMediaPayResult("wechat", state, prepareBean);
//            }
//        }
//        if (Constant.MESSAGE_PAY_SUCCESS == resultCode) {//wechat
//            WechatResult wechatResult = (WechatResult) eventCenter.getMsg();
//            PrepareBean prepareBean = wechatResult.getPrepareBean();
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_SHOP) {
//                handlePayResult(prepareBean, "wechat");
//            }
//            if (prepareBean.getPayTyp() == PrepareBean.PAYTYPE_MEDIA) {
//                handleMediaPayResult("wechat", success, prepareBean);
//            }
//        }
//    }

//    private void handleMediaPayResult(String method, int state, PrepareBean prepareBean) {
//        String tail = "/payresult.html?isPay=%s&order=%s&orgin=0";
//        String orderNo = prepareBean.orderNo;
//        String webUrl = "";
//        switch (state) {
//            case failed:
//                webUrl = String.format(tail, "false", orderNo);
//                break;
//            case success:
//                webUrl = String.format(tail, "true", orderNo);
//                break;
//            case cancel:
//                webUrl = String.format(tail, "false", orderNo);
//                break;
//            default:
//                Logger.e(TAG, "undefind state state is" + state);
//                break;
//        }
//        webUrl = Constant.MEDIA_HOST + webUrl;
//        Logger.i(TAG, "handleMediaPayResult webUrl is >> " + webUrl);
//        MainActivity activity = (MainActivity) getActivity();
//        activity.getWebContent().loadUrl(webUrl);
//    }
//
//    private void handlePayResult(PrepareBean prepareBean, String method) {
//        String orgion = prepareBean.curOrderOrgion;
//        String webUrl = "";
//        if ("1".equals(orgion)) {
//            webUrl = Constant.HOTEL_ORDERS;
//        } else if ("2".equals(orgion)) {
//            webUrl = Constant.NEAR_ORDERS;
//        } else if ("3".equals(orgion)) {
//            webUrl = Constant.SHOP_ORDER;
//        }else {
//            Logger.i(TAG, "curOrderOrgion undefind >> curOrderOrgion = " + orgion);
//        }
//        webUrl = Constant.URL_HOST + webUrl + Constant.ORGIN;
//        Logger.i(TAG, "paymethod is " + method + " >> webUrl is " + webUrl + "webview is null " + (webView == null) + "Thread " + Thread.currentThread().getName());
//        ((MainActivity)getActivity()).getWebContent().loadUrl(webUrl);
//    }

    public void destory() {
        EventBus.getDefault().unregister(this);
        if (provider != null) {

        }
    }

    public void onActivityResult(int requestCode, int resultCode, final Intent data) {


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(Object o) {

    }


}
